
//
//  MessageController.m
//  PropertyMananger
//
//  Created by Mansion on 17/3/5.
//  Copyright © 2017年 BH. All rights reserved.
//

#import "MessageController.h"
#import "HXSearchBar.h"
#import "MessageCell.h"
#import "MessageModel.h"
#import "MessageDetController.h"
@interface MessageController ()<UISearchBarDelegate>

@property (nonatomic,strong) NSMutableArray * messageArray;

@end

@implementation MessageController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initTitleViewName:@"消息"];
    
    [self addSearchBar];
    
    self.searchStr = @"";
    
    self.messageArray = [[NSMutableArray alloc]init];
    
    [self initTableViewWithView:self.view frame:CGRectMake(0, 50, BHscreenW, BHscreenH - 64 - 50) isGroup:NO];
    
    [self createRefresh];
    
    [self createPlaceHolder];
    
    [self postMessageData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return self.messageArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MessageCell * cell = [MessageCell cellWithTableView:tableView];

    MessageModel * model = self.messageArray[indexPath.section];
    
    cell.model = model;
   
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 150;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 15;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    MessageModel * model = self.messageArray[indexPath.section];
    MessageDetController * messageDetailVC = [[MessageDetController alloc]init];
    messageDetailVC.navTitle = model.Title;
    messageDetailVC.model = model;
    [self.navigationController pushViewController:messageDetailVC animated:YES];

}
//添加搜索条
- (void)addSearchBar {
    //加上 搜索栏
    HXSearchBar *searchBar = [[HXSearchBar alloc] initWithFrame:CGRectMake(10, 7.5, self.view.frame.size.width - 20, 35)];
    searchBar.backgroundColor = [UIColor clearColor];
    searchBar.delegate = self;
    //输入框提示
    searchBar.placeholder = @"请输入关键字";
    //光标颜色
    searchBar.cursorColor = BHColor(102, 102, 102);
    //TextField
    searchBar.searchBarTextField.layer.cornerRadius = 4;
    searchBar.searchBarTextField.layer.masksToBounds = YES;
    searchBar.searchBarTextField.layer.borderColor = [UIColor grayColor].CGColor;
    searchBar.searchBarTextField.layer.borderWidth = 0.5;
    
    //清除按钮图标
    // searchBar.clearButtonImage = [UIImage imageNamed:@"demand_delete"];
    
    //去掉取消按钮灰色背景
    searchBar.hideSearchBarBackgroundImage = YES;
    
    [self.view addSubview:searchBar];
}

#pragma mark - UISearchBar Delegate
- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    if (range.location == 0) {
        
        [self.resultArr removeAllObjects];
        [self.tableView reloadData];
    }
    return YES;
}
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    
    return YES;
}
//已经开始编辑时的回调
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    HXSearchBar *sear = (HXSearchBar *)searchBar;
    //取消按钮
    sear.cancleButton.backgroundColor = [UIColor clearColor];
    [sear.cancleButton setTitle:@"取消" forState:UIControlStateNormal];
    [sear.cancleButton setTitleColor:BHColor(102, 102, 102) forState:UIControlStateNormal];
    sear.cancleButton.titleLabel.font = [UIFont systemFontOfSize:14];
}

//搜索按钮
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
    self.isDown = YES;
    
    [self.tableView.mj_header beginRefreshing];
    
    [self postMessageData];
    
     [self.view endEditing:YES];
}

//取消按钮点击的回调
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    searchBar.showsCancelButton = NO;
    searchBar.text = nil;
    self.isSearch = NO;
    
    self.isDown = YES;
    self.nextPage = 1;
    
    [self postMessageData];
    
    self.searchStr = @"";

    [searchBar resignFirstResponder];
    
    [self.view endEditing:YES];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    self.isDown = YES;
    [self.messageArray removeAllObjects];
    [self.searchBar resignFirstResponder];
    
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.tableView endEditing:YES];
    [self.view resignFirstResponder];
    [self.view endEditing:YES];
    self.isSearch = NO;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    if (searchText.length == 0) {
        
        self.searchText = @"";
        self.isSearch = NO;
        self.placehoderImg.hidden = YES;
        self.titleLabel.hidden = YES;
        
         [self.tableView.mj_header beginRefreshing];
        
        [self.resultArr removeAllObjects];
        [self.tableView reloadData];
    }
//    else{
//        
//        [self.tableView.mj_header beginRefreshing];
//
//    }
    
    self.searchStr = searchText;
    [self.resultArr removeAllObjects];
    [self.messageArray removeAllObjects];
    
    [self.tableView reloadData];
    
    for (MessageModel * model in self.messageArray) {
        if ([model.PublishTime rangeOfString:searchText].location != NSNotFound) {
            [self.resultArr addObject:model.PublishTime];
        }
    }
    
    if (self.resultArr.count) {
        self.isSearch = YES;
        self.placehoderImg.hidden = YES;
        self.titleLabel.hidden = YES;
        [self.tableView reloadData];
    }
    
}

#pragma mark - 创建刷新UI
- (void)createRefresh{
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        self.nextPage = 1;
        
        self.isDown = YES;
        //获取数据
        [self postMessageData];
        
    }];
    
    //上拉刷新
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        self.nextPage += 1;
        
        self.isDown = NO;
        //获取数据
        [self postMessageData];
        
        //    [self.tableView.mj_footer endRefreshingWithNoMoreData];
        
    }];
}
#pragma mark - 暂未图
- (void)createPlaceHolder
{
    
    self.placehoderImg = [[UIImageView alloc]init];
    [self.tableView addSubview:self.placehoderImg];
    self.placehoderImg.image = [UIImage imageNamed:@"ico_query_no"];
    
    [self.placehoderImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.tableView).with.offset(0);
        make.top.equalTo(self.tableView.mas_bottom).with.offset(100);
        make.size.mas_equalTo(CGSizeMake(80, 80));
    }];
    
    self.titleLabel = [[UILabel alloc]init];
    [self.tableView addSubview:self.titleLabel];
    self.titleLabel.text = @"暂无消息内容";
    
    self.titleLabel.textColor= BHColor(153, 153, 153);
    self.titleLabel.font = BHFont(15);
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.tableView).with.offset(0);
        make.top.equalTo(self.placehoderImg.mas_bottom).with.offset(10);
        make.size.mas_equalTo(CGSizeMake(100, 25));
    }];
    
}
#pragma mark - 消息数据
- (void)postMessageData{

    NSDictionary * parms = @{
                             @"CommunityID":userModel.CommunityID,
                             @"Key":self.searchStr,
                             @"NoticeType":@"3",
                             @"UserID":@"0",
                             @"CurPage":[NSString stringWithFormat:@"%ld",self.nextPage],
                             @"json":@"\{\"jsonEntity\":\{},\"action\":\"noticelist\",\"version\":\"V1.0\"}"};
    DLog(@"领导提交的参数===%@",parms);
    
    [HomeNetWorkRequest postHomeMessageSuccess:^(id data) {
        
        if (self.isDown == YES) {
            
            [self.messageArray removeAllObjects];
            self.isDown = NO;
        }
        
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSString * str = [NSString stringWithFormat:@"%@",dict[@"Data"]];
        NSData * data2 = [str dataUsingEncoding:NSUTF8StringEncoding];
        NSArray * array = [NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];
        DLog(@"消息数据 == %@",array);
        
        DLog(@"%@",dict[@"Msg"]);
        
     
        for (NSDictionary * dict in array) {
            
            MessageModel * model = [[MessageModel alloc]init];
            [model setValuesForKeysWithDictionary:dict];
            
            [self.messageArray addObject:model];
        }
        
        if (self.messageArray.count != 0){
            
            self.placehoderImg.hidden = YES;
            self.titleLabel.hidden = YES;
            
        }else{
            
         //   self.tableView.mj_footer.hidden = YES;
            
            self.placehoderImg.hidden = NO;
            self.titleLabel.hidden = NO;
        }
        
//        if (self.messageArray.count <=4) {
//            self.tableView.mj_footer.hidden = YES;
//        }
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        [MBProgressHUD hideHUDForView:self.view];
        
        
        [self.tableView reloadData];
        
    } Fail:^(NSString *errorDes) {
        
        [MBProgressHUD hideHUDForView:self.view];
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
         [MBProgressHUD hideHUD];
        
    } param:parms];


}


@end
